<template>
  <swiper :options="swiperOption" :key="keyId">
    <slot></slot>
    <div class="swiper-pagination" v-if="pagination" slot="pagination"></div>
  </swiper>
</template>

<script>
  import {swiper} from 'vue-awesome-swiper';
  export default {
    name: 'MeSlider',
    components: {
      swiper
    },
    props: {
      direction: {
        type: String,
        default: 'horizontal',
        validator(value) {
          return [
            'horizontal',
            'vertical'
          ].indexOf(value) > -1;
        }
      },
      interval: {
        type: Number,
        default: 3000,
        validator(value) {
          return value >= 0;
        }
      },
      loop: {
        type: Boolean,
        default: true

      },
      pagination: {
        type: Boolean,
        default: true
      },
      data: {
        type: Array,
        default() {
          return [];
        }
      }
    },
    watch: {
      data(newData) {
        if (newData.length === 0) {
          return;
        }
        this.swiperOption.loop = !(newData.length === 1);
        this.keyId = Math.random();
      }
    },
    data() {
      return {
        keyId: Math.random()
      };
    },
    created() {
      this.init();
    },
    methods: {
      init() {
        this.swiperOption = {
          watchOverflow: true, // 如果只有一张图片，那么就禁止滑动
          direction: this.direction,
          autoplay: this.interval ? {
            delay: this.interval,
            disableOnInteraction: false // 一旦有交互就停止轮播
          } : false,
          slidePerView: 1, // 容器同时显示几张图片
          loop: !(this.data.length <= 1), // 是否开启无缝滚动
          pagination: {
            el: this.pagination ? '.swiper-pagination' : null
          // le表示分页器的元素
          }
        };
      }
    }
  };
</script>

<style scoped lang="scss">
  .swiper-container {
    height: 100% ;
    width: 100%;
  }

</style>
